import json
import os
import socket
import sys


def get_python_path():
    """
    获取python路径
    :return:
    """
    host_name = socket.gethostname()
    if host_name == "legend":
        python_path = "/home/legend/WorkSpace/python/water_applets/"
    if host_name == "ecs-364582":
        python_path = "/root/water_applets/"
    else:
        python_path = ""
    return python_path


sys.path.append(get_python_path())
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "water_applets.settings")
django.setup()
from models.models import RegionInfo


def get_regin_data():
    with open("city.json", "r") as file:
        data = json.load(file)
        number = 1
        sql_data = []
        for item in data:
            province_tmp = {
                "id": number,
                "parent_id": 0,
                "name": item["province"]
            }
            province_id = number
            sql_data.append(province_tmp)
            number += 1
            for city in item['citys']:
                city_temp = {
                    "id": number,
                    "parent_id": province_id,
                    "name": city['city']
                }
                city_id = number
                sql_data.append(city_temp)
                number += 1
                for area in city['areas']:
                    area_temp = {
                        "id": number,
                        "parent_id": city_id,
                        "name": area['area']
                    }
                    sql_data.append(area_temp)
                    number += 1
    return sql_data


def insert_data():
    RegionInfo.objects.all().delete()
    sql_data = get_regin_data()
    for item in sql_data:
        RegionInfo.objects.create(**item)


if __name__ == '__main__':
    insert_data()
